package com.iking.housekeeping.controller.servicerecord;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import com.iking.housekeeping.entity.dept.SysDept;
import com.iking.housekeeping.httpbean.servicerecord.*;
import com.iking.housekeeping.service.dept.DeptService;
import com.iking.housekeeping.service.user.LoginService;
import com.iking.housekeeping.util.token.WebTokenUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.Page;
import com.iking.housekeeping.common.CodeEnum;
import com.iking.housekeeping.common.PageResult;
import com.iking.housekeeping.common.ReturnCode;
import com.iking.housekeeping.dao.servicestaff.ServiceStaffMapper;
import com.iking.housekeeping.dao.user.SysUserMapper;
import com.iking.housekeeping.entity.dtuser.DeptUser;
import com.iking.housekeeping.entity.servicerecord.ServiceRecord;
import com.iking.housekeeping.httpbean.elderlyres.UpdateElderly;
import com.iking.housekeeping.service.elderly.ElderlyService;
import com.iking.housekeeping.entity.servicestaff.ServiceStaff;
import com.iking.housekeeping.entity.user.SysUser;
import com.iking.housekeeping.httpbean.servicerecord.ReqServiceRecord;
import com.iking.housekeeping.httpbean.elderlyres.UpdateElderly;
import com.iking.housekeeping.httpbean.servicerecord.DetilServiceRecord;
import com.iking.housekeeping.httpbean.servicerecord.HttpServiceRecord;
import com.iking.housekeeping.httpbean.servicerecord.HttpVisitedRecord;
import com.iking.housekeeping.httpbean.servicerecord.SelectServiceRecord;
import com.iking.housekeeping.httpbean.servicerecord.ReqStatisticsBean;
import com.iking.housekeeping.httpbean.servicerecord.ResStatisticsBean;
import com.iking.housekeeping.service.dtuser.DeptUserService;
import com.iking.housekeeping.service.servicerecord.ServiceRecordService;
import com.iking.housekeeping.util.UUIDUtil;
import com.iking.housekeeping.util.token.WebTokenUtil;

/**
 * 服务记录
 * 
 * @author: gf
 * @date: 2018年4月22日 下午6:38:56
 */
@RestController
@RequestMapping("/serviceRecord")
public class ServiceRecordController {
	
	@Autowired 
	private DeptUserService deptUserService;
	
	@Autowired 
	private ServiceStaffMapper serviceStaffMapper;

	@Autowired
	private DeptService deptService;

	@Autowired
	private LoginService loginService;
	/**
	 * 服务记录操作
	 */
	@Autowired
	private ServiceRecordService serviceRecordService; 
	
	/**
	 * 添加
	 * 
	 * @param req
	 * @param bindingResult
	 * @return ReturnCode
	 * @author gf
	 */
	@PostMapping("/insert")
	public ReturnCode insert(@RequestBody @Valid ServiceRecord req, BindingResult bindingResult) {
		// 参数验证
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.NOT_DATA, msg);
		}
		req.setfId(UUIDUtil.getUUID());
		// 执行添加
		if (serviceRecordService.insert(req) < 1) {
			return new ReturnCode(CodeEnum.FAIL);
		}
		return new ReturnCode(CodeEnum.SUCCESS, req);
	}

	/**
	 * 删除
	 * 
	 * @param list
	 * @return ReturnCode
	 * @author gf
	 */
	@PostMapping("/deleteBatch")
	public ReturnCode deleteBatch(@RequestBody List<String> list) {
		List<String> stringStat=serviceRecordService.selectState(list);
		if(stringStat.size()>0){
			return new ReturnCode(CodeEnum.FAIL, "此任务正在执行中，请选择其他数据！", null);
		}else{
		if (serviceRecordService.deleteBatch(list) != list.size()) {
			return new ReturnCode(CodeEnum.FAIL, "操作失败！", null);
		}
		return new ReturnCode(CodeEnum.SUCCESS, "操作成功！", null);
		}
	}

	/**
	 * 更新
	 *
	 * @param req
	 * @param bindingResult
	 * @return ReturnCode
	 * @author gf
	 */
	@PostMapping("/update")
	public ReturnCode update(@RequestBody @Valid ServiceRecord req, HttpServletRequest request, BindingResult bindingResult) {
		// 参数验证
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.NOT_DATA, msg);
		}
		serviceRecordService.updateServiceRecord(req, request);
		return new ReturnCode(CodeEnum.SUCCESS);
	}

	/**
	 * 分页查询所有
	 * 
	 * @param selectServiceRecord
	 * @return ReturnCode
	 * @author gf
	 */
	@PostMapping("/seleteAll")
	public ReturnCode selectAll(@RequestBody SelectServiceRecord selectServiceRecord, javax.servlet.http.HttpServletRequest request ) {
		// 获取当前登录人id
		String userId = WebTokenUtil.getUserIdByRequest(request);
		List<SysDept> menuList = deptService.selectAdminById(userId);
		int result=loginService.select(selectServiceRecord.getfStreetCommunity(),menuList);
		if(result==0){
			return new ReturnCode(CodeEnum.FAIL,"您没有该区域查看权限！", null);
		}else if(result==1){
			selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
		}else if(result==2){
			selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
		}else if(result==3){
			selectServiceRecord.setfStreetCommunity(menuList.get(0).getfId());
		}
		Page<HttpServiceRecord> httpServiceRecordPage = serviceRecordService.selectByPage(selectServiceRecord);
		return new ReturnCode(CodeEnum.SUCCESS, new PageResult<HttpServiceRecord>(httpServiceRecordPage));
	}
	/**
	 * 
	 * @Description:
	 * @author:秦
	 * @param reqServiceRecord
	 * @param request
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/addAppointment")
	public ReturnCode addAppointment(@RequestBody @Valid ReqServiceRecord reqServiceRecord, HttpServletRequest request,
			BindingResult bindingResult) {
		// 参数不为空验证
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL_EARROR_PARM, msg, null);
		}
		int result = serviceRecordService.addServiceRecord(reqServiceRecord, request);
		if(result < 1) {
			return new ReturnCode(CodeEnum.FAIL,null);
		}else  if(result ==3){
			return new ReturnCode(CodeEnum.FAIL,"您的服务次数已用完",null);
		}
		return new ReturnCode(CodeEnum.SUCCESS, null);
	}

	/**
	 * 
	 * @Description:
	 * @author:CGZ
	 * @param updateElderly
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/updateElderly")
	public ReturnCode updateElderly(@RequestBody @Valid UpdateElderly updateElderly, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL_EARROR_PARM, msg);
		}
        DetilServiceRecord  detilServiceRecord=serviceRecordService.selectServiceRecord(updateElderly.getfId());
		if(detilServiceRecord == null){
            return new ReturnCode(CodeEnum.FAIL, "该预约任务已被取消，请刷新页面！",null);
        }
		updateElderly.setfStartTime(new Date());
		ServiceRecord sRecord = new ServiceRecord(updateElderly);
		//修改状态为服务中
		sRecord.setfState("795b6e37d8fa45e489e8e8709865a131");
		int result = serviceRecordService.updateByPrimaryKeySelective(sRecord);
		if (result == 0) {
			return new ReturnCode(CodeEnum.NOT_DATA, null);
		}
		return new ReturnCode(CodeEnum.SUCCESS, sRecord);
	}

	/**
	 * 
	 * @Description:结束服务
	 * @author:CGZ
	 * @param serviceRecord
	 * @return
	 */
	@PostMapping("/endService")
	public ReturnCode endService(@RequestBody @Valid ServiceRecord serviceRecord, HttpServletRequest request,
			BindingResult bindingResult) {
		// 参数不为空验证
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode(CodeEnum.FAIL_EARROR_PARM, msg, null);
		}
		serviceRecord.setfState("a73dc44418ae4e7e867363d05ea316a6");
		serviceRecord.setfEndTime(new Date());
		int result=serviceRecordService.endServiceRecord(serviceRecord, request);
		if(result < 1) {
			return new ReturnCode(CodeEnum.FAIL,null);
		}else  if(result ==3){
			return new ReturnCode(CodeEnum.FAIL,"该老人的服务次数已用完",null);
		}
		return new ReturnCode(CodeEnum.SUCCESS);
	}
	
	/**
	 * 	回访展示
	 *  @return ReturnCode
	 *  @author gf
	 */
	@PostMapping("/visited")
	public ReturnCode visited(HttpServletRequest request) {
        //获取当前登录人id
		String userId = WebTokenUtil.getUserIdByRequest(request);
		List<SysDept> menuList = deptService.selectAdminById(userId);
		List list = deptService.selectAdminById(userId);
		HttpVisitedRecord httpVisitedRecord =new HttpVisitedRecord();
		//判断当前登录人是否为区域管理员
		if("".equals(menuList.get(0).getfDeptPCode()) ||menuList.get(0).getfDeptPCode() == null){
			//查看所有区域数据
			httpVisitedRecord.setfStreetCommunity(menuList.get(0).getfId());
		}else{
		if(list.contains(menuList.get(0).getfDeptPCode()) || menuList.get(0).getfAdminUser()!=""){
			//查看二级服务数据
			httpVisitedRecord.setfStreetCommunity(menuList.get(0).getfId());
			}else{
			//查看自己社区服务数据
			httpVisitedRecord.setfStreetCommunity(menuList.get(0).getfId());
			}
		}
		List<HttpVisitedRecord> visitedRecord = serviceRecordService.visitedRecord(httpVisitedRecord);
		return new ReturnCode(CodeEnum.SUCCESS, "回访展示", visitedRecord);
	}
	
	/**
	 * 根据服务id查询服务记录详情
	 * @param fId
	 * @return
	 */
	@GetMapping("/selectServiceRecord/{fId}")
	public ReturnCode selectServiceRecord(@PathVariable("fId") String fId) {
		DetilServiceRecord detilServiceRecord = serviceRecordService.selectServiceRecord(fId);
		if(detilServiceRecord == null) {
			return new ReturnCode(CodeEnum.FAIL,"查询失败", null);
		}
		return new ReturnCode(CodeEnum.SUCCESS, "查询成功", detilServiceRecord);
	}

	/**
	 * 
	 * @Description:统计未完成
	 * @author:CGZ
	 * @param request
	 * @return
	 */
	@GetMapping("/undone")
	public ReturnCode undone(HttpServletRequest request){
		Integer totalNum = 0;
		Integer undoneNum = 0;
		Integer completedNum = 0;
		//查询总订单数量
		DeptUser deptUser = deptUserService.selectbyUserId(WebTokenUtil.getUserIdByRequest(request));
		if(deptUser == null) {
			return new ReturnCode(CodeEnum.NOT_DATA);
		}
		//查询所有的服务人员
		List<ServiceStaff>  serviceStaffList = serviceStaffMapper.selectAllList();
		List<ServiceStaff> list = new ArrayList<>();
		for(int i = 0;i < serviceStaffList.size(); i++) {
			ServiceStaff serviceStaff = serviceStaffList.get(i);
			if(serviceStaff.getfStreetCommunity().contains(deptUser.getfDeptId())) {
				list.add(serviceStaff);
			}
		}
		ReqStatisticsBean reqStatisticsBean = new ReqStatisticsBean();
		for (ServiceStaff serviceStaff : list) {
			reqStatisticsBean.setUserId(serviceStaff.getfId());
			totalNum += serviceRecordService.selectTotal(reqStatisticsBean);
			undoneNum += serviceRecordService.selectUndone(reqStatisticsBean);
			completedNum += serviceRecordService.selectCompleted(reqStatisticsBean);
		}
		System.err.println(totalNum);
		System.err.println(undoneNum);
		System.err.println(completedNum);
		
		ResStatisticsBean resStatisticsBean = new ResStatisticsBean();
		resStatisticsBean.setTotalNum(totalNum);
		resStatisticsBean.setUndoneNum(undoneNum);
		resStatisticsBean.setCompletedNum(completedNum);
		return new ReturnCode(CodeEnum.SUCCESS, "查询成功", resStatisticsBean);
	}
	
}
